package amani.wechat.platform.controller;

import java.io.*; 
import java.util.ArrayList; 
import java.util.Iterator;
import java.util.List;  
import javax.servlet.http.*;
 
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; 

import amani.wechat.platform.webserviceClient.imageService.ImageCloudService;
import amani.wechat.platform.webserviceClient.imageService.ImageCloudServicePortType;
 

@Controller
@RequestMapping(value = "/imagecloud")
public class UploadFileController {
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void handleFormUpload(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType("text/html;charset=UTF-8");
		String erroresultFomat ="result:{isOk:'false',errorMsg:'%s'}";
		try { 
			final long MAX_SIZE = 7 * 1024 * 1024;// 设置上传文件最大为 3M
			// 允许上传的文件格式的列表
			final String[] allowedExt = new String[] { "jpg", "jpeg", "gif","png","bpm","ico" };		
			 
			// 设置字符编码为UTF-8, 这样支持汉字显示
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/json; charset=UTF-8");  
			// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload 
			DiskFileItemFactory dfif = new DiskFileItemFactory();
			dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
		 
			// 用以上工厂实例化上传组件
			ServletFileUpload sfu = new ServletFileUpload(dfif);
			// 设置最大上传尺寸
			sfu.setSizeMax(MAX_SIZE); 
			// 从request得到 所有 上传域的列表
			List<FileItem> fileList = null;
		
			try {
				fileList = sfu.parseRequest(request);
			} catch (FileUploadException e) {// 处理文件尺寸过大异常
				if (e instanceof SizeLimitExceededException) { 
					String json =String.format( erroresultFomat,"文件尺寸超过规定大小");
					response.getOutputStream().write( json.getBytes("UTF-8"));  
					return;
				} 
				e.printStackTrace();
				String json =String.format( erroresultFomat,e.getMessage());
				response.getOutputStream().write( json.getBytes("UTF-8"));  
				return; 
			}catch (Exception e) {
				String json =String.format( erroresultFomat,e.getMessage());
				response.getOutputStream().write( json.getBytes("UTF-8"));  
				return;  
			}
		
			// 没有文件上传
			if (fileList == null || fileList.size() == 0) {
				String json =String.format( erroresultFomat,"没有上传文件，请选择上传文件");
				response.getOutputStream().write( json.getBytes("UTF-8"));  
				return;  
			}
			//获取所有参数和文件
			String mainFolder=null;
			ArrayList<String> fileNos=new ArrayList<String>(); 
			ArrayList<FileItem> files=new ArrayList<FileItem>();
			Iterator<FileItem> fileItr = fileList.iterator();
			while (fileItr.hasNext()) {
				FileItem fileItem = null; 
				// 得到当前文件
				fileItem = (FileItem) fileItr.next();
				// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
				if (fileItem.isFormField()) {
					String formname=fileItem.getFieldName();//获取form中的名字
					String formcontent=fileItem.getString();
					formname=new String(formname.getBytes(),"UTF-8");
					formcontent=new String(formcontent.getBytes(),"UTF-8");
					if ("folderName".equals(formname)) {
						mainFolder=formcontent;
					}else {
						fileNos.add(formcontent);
					}
					 
				}else {
					// 得到文件的完整路径  
					String  path = fileItem.getName();  
					 // 得到去除路径的文件名  
			        String t_name = path.substring(path.lastIndexOf("\\") + 1);  
					// 得到文件的扩展名(无扩展名时将得到全名)  
			        String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); 
			        // 拒绝接受规定文件格式之外的文件类型
					boolean allowFlag=false;
					int allowedExtCount = allowedExt.length;
					for (int i=0; i < allowedExtCount; i++) {
						if (allowedExt[i].equals(t_ext)){
							allowFlag=true;
							break;
						}
					}
					if (!allowFlag) { 
						String json =String.format( erroresultFomat,String.format("上传的文件{%s}格式不支持，必须是以下格式(jpg, jpeg, gif,png,bpm)",t_name));
						response.getOutputStream().write( json.getBytes("UTF-8"));  
						return;   
					}
					if ( fileItem.getSize()>0) {
						files.add(fileItem);
					}
				}
			}
			//参数检查
			if (mainFolder==null) {
				String json =String.format( erroresultFomat,"没有设定上传文件的目录");
				response.getOutputStream().write( json.getBytes("UTF-8"));  
				return;    
			}
		 
			if (fileNos.size()  !=files.size()) { 
				String json =String.format( erroresultFomat,String.format("上传的文件个数{%s}和设定的文件编号个数(%s)不一致", files.size(),fileNos.size())); 
				response.getOutputStream().write( json.getBytes("UTF-8"));  
				return;   
			}
			
			ImageCloudService imageCloudService =new ImageCloudService();
			ImageCloudServicePortType client =imageCloudService.getImageCloudServiceHttpPort();
			// 循环处理所有文件   
			String result="result:{isOk:'true',files:[";
			for (int i = 0; i < files.size(); i++) {
				FileItem fileItem = files.get(i);
				String fileNoString=fileNos.get(i); 
				try {
				   String uploadResult=  client.uploadFile(fileItem.get(),"test", mainFolder+"/"+fileNoString);
				   result+=uploadResult+",";
				} catch (Exception e) {
					String json =String.format( erroresultFomat,e.getMessage());
					response.getOutputStream().write( json.getBytes("UTF-8"));  
					return;  
				}
			}
			result=result.substring(0, result.length()-1)+"]}";
			response.getOutputStream().write( result.getBytes("UTF-8"));  
			return;
//			String folderName = request.getParameter("folderName");
//			String newFileName = request.getParameter("fileName");
////			PrintWriter writer = response.getWriter();
//			Collection<Part> parts = request.getParts();
//			ImageCloudService imageCloudService =new ImageCloudService();
//			ImageCloudServicePortType client =imageCloudService.getImageCloudServiceHttpPort();
//		 
//			int i = 0;
//			for (Part part : parts) {
//				if (part.getContentType() != null) {
//					String fileName = getFileName(part);
//					if (fileName != null && !fileName.isEmpty()) {
//						i++;
//						newFileName = newFileName + i;
//						client.uploadFile(readInputStream(part.getInputStream()),
//								QiniuConfig.getDefaultBucket(), folderName
//										+ "/" + newFileName);
//					 
//					}
//				}
//			}
		} catch (Exception e) {
		 
				// TODO Auto-generated catch block
				e.printStackTrace();
			 
		}
		 
	}

	/**
	 * 从输入流中读取数据
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();// 网页的二进制数据
		outStream.close();
		inStream.close();
		return data;
	}

	private String getFileName(Part part) {
		String contentDispositionHeaderString = part
				.getHeader("content-disposition");
		String[] elements = contentDispositionHeaderString.split(";");
		for (String element : elements) {
			if (element.trim().startsWith("filename")) {
				return element.substring(element.indexOf('=') + 1).trim()
						.replace("\"", "");
			}
		}
		return null;
	}

	@RequestMapping("/uploadfile")
	public void uploadfile() {

	}
}
